package com.ubi.core.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

/**
 * <p>
 * 模仿Guava的Lists类写的工具类
 * </p>
 * <p>
 * <a href=
 * "https://github.com/hceylan/guava/blob/master/guava/src/com/google/common/collect/Lists.java"
 * >{@code 源码链接}</a>
 * </p>
 * <p>
 * <a href=
 * "http://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained#Lists"
 * >{@code Guava, Lists的使用指南}</a>
 * </p>
 *
 * @author cwt
 */
public final class ListUtils {

    public static <E> List<E> newArrayList() {
        return new ArrayList<>();
    }

    public static <E> List<E> asList(E... elements) {
        ArrayList<E> list = new ArrayList<>();
        if (elements != null && elements.length > 0) {
            Collections.addAll(list, elements);
        }
        return list;
    }

    public static <E> List<E> asList(Iterator<? extends E> elements) {
        List<E> list = newArrayList();
        if (elements != null) {
            while (elements.hasNext()) {
                list.add(elements.next());
            }
        }
        return list;
    }

    public static <E> String listToString(Collection<E> list, char separator) {
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        StringBuilder sb = new StringBuilder();
        for (E e : list) {
            sb.append(e).append(separator);
        }
        return sb.toString().substring(0, sb.toString().length() - 1);
    }
}
